/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Zeshui Xu<i@xuzeshui.com>
 * Created Time: 2015-10-06 21:08:50
 * Last Modified: 2016-08-19 09:49:02
 * File Name: controllers/jdxg.go
 * Description:家电小哥后台绑定微信
 */
package controllers

import (
	"encoding/json"

	"doubimeizhi.com/utility"

	"passport/auth"
	"passport/errorcode"
	"passport/login"

	log "github.com/cihub/seelog"
)

type JDXGController struct {
	BackendAdminController
}

/*
	第三方绑定
*/
func (p *JDXGController) ThirdAccountBind() {
	defer p.Output("ThirdAccountBind")

	body := p.Ctx.Input.RequestBody
	log.Debugf("recv body: %s", string(body))
	var reqBody login.ThirdAccountBindLoginReq
	if err := json.Unmarshal(body, &reqBody); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}
	if reqBody.RegIp == "" {
		reqBody.RegIp = p.Ctx.Input.IP()
	}
	reqBody.RegPlat = auth.GetAuthAppKeyService().GetPlat(p.AppKey)
	reqBody.NeedLogin = false //不需要登录

	if reqBody.ExtId == "" {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = "openid不能为空"
		return
	}

	if reqBody.Mobile == "" || !utility.IsValidMainlandMobile(reqBody.Mobile) {
		p.Resp["code"] = errorcode.EC_CAPTCHA_INVALID_MOBILE_NUMBER
		p.Resp["msg"] = "invalid mobile number"
		return
	}

	code, msg, respBody := login.GetLoginService().ThirdAccountBindLogin(&reqBody)
	p.Resp["code"] = code
	p.Resp["msg"] = msg
	if errorcode.EC_GL_SUCCESS == code {
		p.Resp["user_id"] = respBody.Userid
		p.Resp["access_token"] = respBody.AccessToken
		p.Resp["expire_second"] = respBody.ExpireSecond
		p.Resp["hx_account"] = respBody.HXAccount
		p.Resp["hx_passwd"] = respBody.HXPasswd
	}
}
